import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import {
    ProForm,
    ProFormText,
    ProFormSelect,
    ProFormUploadButton,
    ProFormTextArea,
    ProFormItem,
    ProFormGroup
} from '@ant-design/pro-components';
import { Button, Select, Upload, UploadFile, message } from 'antd';
import type { GetProp, UploadProps } from 'antd';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

import { QiniuFileUpload, Tags } from '../../../../components';
import { getNowFormatDate, homePath, uuid, uuidTrim } from '../../../../utils';
import { PROJECT_APPLICATION_CLASS_IDENTIFIER, PROJECT_CLASS_IDENTIFIER } from '@/services/constants';
import { appCreateEmptyApplication, appUpdateApplicationFiles, dsInsert, dsUpdateById, PROJECT_APPLICATION_TYPE_SELECT_OPTIONS, ProjectApplication, ProjectApplicationType } from '@/services/local';
import { writeFile, BaseDirectory } from '@tauri-apps/plugin-fs';

export interface ProjectApplicationEditorProps {
    style?: CSSProperties;
    projectIdentifier: string;
    item?: ProjectApplication;
    onFinish: () => Promise<void> | void;
}

export const ProjectApplicationEditor: React.FC<ProjectApplicationEditorProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [icon, setIcon] = useState<Array<string>>([]);

    const [fileList, setFileList] = useState<UploadFile[]>([]);

    const requestCallback = useCallback(async () => {
        console.log('---------', props.item);
        if (!props.item) return {};
        if (props.item.icon && props.item.icon.length > 0) {
            setIcon([props.item.icon]);
        }
        return props.item;
    }, [props.item]);

    useEffect(() => { }, [props.item])

    const beforeUpload = (file: FileType) => {
        const isZip = file.type === 'application/zip';
        if (!isZip) {
            message.error('文件需要zip格式!');
        }
        const isLt2M = file.size / 1024 / 1024 < 50;
        if (!isLt2M) {
            message.error('文件需要小于60MB!');
        }
        return isZip && isLt2M;
    };

    return (
        <Container>
            <ProForm<ProjectApplication>
                initialValues={props.item}
                request={requestCallback}
                onFinish={async (values) => {
                    //TODO 校验
                    values.icon = icon && icon.length > 0 ? icon[0] : '';

                    values = {
                        project_identifier: props.projectIdentifier,
                        ...props.item,
                        ...values,
                    };
                    console.log(values, fileList);

                    if (props.item) {
                        //更新文件
                        if (fileList && fileList.length > 0) {
                            values.path = await appUpdateApplicationFiles(props.projectIdentifier, values.identifier, fileList[0]);
                        }
                        let _ = dsUpdateById(0, PROJECT_APPLICATION_CLASS_IDENTIFIER, props.item.id, values);
                    } else {
                        //添加
                        values.identifier = uuid();
                        //更新文件
                        if (fileList && fileList.length > 0) {
                            values.path = await appUpdateApplicationFiles(props.projectIdentifier, values.identifier, fileList[0]);
                        }
                        let res = await appCreateEmptyApplication(values);
                    }
                    await props.onFinish();
                }}
                submitter={false}
            >
                <ProFormGroup>
                    <ProFormText
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="name"
                        label="名称" />

                    <ProFormText
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="title"
                        label="标题" />
                    <ProFormSelect
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        options={PROJECT_APPLICATION_TYPE_SELECT_OPTIONS}
                        name="application_type"
                        label="应用类型" />
                </ProFormGroup>

                <ProFormGroup>
                    <ProFormItem
                        extra="只能上传jpg/png文件,且不大于1MB"
                        label="图标"
                        name="icon">
                        <QiniuFileUpload
                            title={'上传图标'}
                            listType={'picture-card'}
                            accept={"image/png, image/jpeg"}
                            max={1}
                            values={icon}
                            isPicture={true}
                            filePath={`g01/domains/images/${getNowFormatDate('')}`}
                            onChange={async (files) => {
                                setIcon(files);
                            }}></QiniuFileUpload>
                    </ProFormItem>
                    <Upload
                        multiple={false}
                        maxCount={1}
                        accept={'application/zip'}
                        fileList={fileList}
                        beforeUpload={beforeUpload}
                        customRequest={async (options) => {
                            console.log('-----', options);
                            const { onSuccess, onError, file, onProgress } = options;
                            //创建临时文件
                            let home = await homePath();
                            let filePath = `${home}/temp/`;
                            let fileName = `${uuidTrim()}.zip`;
                            try {
                                onProgress({ percent: 10 });
                                //读取文件保存到临时文件夹
                                let reader = new FileReader();
                                reader.addEventListener('loadend', () => {
                                    console.log('file_result:', reader.result);
                                    //写文件
                                    writeFile(`${filePath}${fileName}`, reader.result).then(() => {
                                        onSuccess({
                                            path: `${filePath}${fileName}`
                                        });
                                    }).catch((err) => {
                                        onError(err, {});
                                    });
                                });
                                reader.addEventListener('progress', (event) => {
                                    onProgress({ percent: event.loaded / event.total * 100 });
                                });
                                reader.readAsArrayBuffer(file as FileType);
                            } catch (error) {
                                onError(error);
                            }
                        }}
                        onChange={({ file, fileList: newFileList }) => {
                            setFileList(newFileList);
                        }}
                    >
                        <Button>{'上传文件'}</Button>
                    </Upload>
                </ProFormGroup>

                <ProFormTextArea
                    fieldProps={{}}
                    name="description"
                    label="描述" />
                <ProFormItem>
                    <Button loading={loading} type="primary" htmlType="submit">
                        添加
                    </Button>
                </ProFormItem>
            </ProForm>
        </Container>
    );
}


const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
`;


export interface ProjectApplicationExtentionProps {
    style?: CSSProperties;
    label: string;
    onFinish?: () => Promise<void> | void;
}

const ProjectApplicationExtention: React.FC<ProjectApplicationExtentionProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [applicationType, setApplicationType] = useState<ProjectApplicationType>(ProjectApplicationType.Agent);

    const [pkg, setPkg] = useState<Array<string>>([]);

    return (
        <ProFormItem label={props.label} shouldUpdate>
            {(form) => {
                return (
                    <>
                        <Select
                            style={{ flex: 1 }}
                            value={form.getFieldValue("application_type") || ProjectApplicationType.Agent}
                            onChange={(value) => {
                                form?.setFieldValue("application_type", value)
                                setApplicationType(value)
                            }}
                            options={PROJECT_APPLICATION_TYPE_SELECT_OPTIONS} />
                        {
                            applicationType === ProjectApplicationType.CustomH5 && (
                                <>
                                    <ProFormUploadButton
                                        extra="只能上传zip文件,且不大于1MB"
                                        label="应用安装包"
                                        name="file"
                                        title="上传安装包"
                                    />
                                </>
                            )
                        }
                    </>
                );
            }}
        </ProFormItem >
    );
}

